package org.example.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.admin.bo.RoleBO;
import org.example.admin.dao.RoleDao;
import org.example.admin.dto.RoleDto;
import org.example.admin.entity.RoleEntity;
import org.example.admin.service.RoleMenuService;
import org.example.admin.service.UserRoleService;
import org.example.admin.vo.RoleVo;
import org.example.admin.vo.UserVo;
import org.example.core.constant.TokenConstants;
import org.example.core.utils.PageUtils;
import org.example.core.utils.R;
import org.example.security.handler.SecurityHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.admin.service.RoleService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private UserRoleService userRoleService;

    // 获取用户角色
    @Override
    public Set<String> getUserRoles(UserVo userVo){
        if (userVo.getId() == 1L){
            Set<String> roles = new HashSet<>();
            roles.add("admin");
            return roles;
        }else{
            List<String> rolesList = roleDao.getRoleByUserId(userVo.getId());
            if (rolesList != null){
                return rolesList.stream().map(String::trim).collect(Collectors.toSet());
            }
            return null;
        }
    }

    // 查询角色列表
    @Override
    public PageUtils list(RoleDto roleDto) {
        if (roleDto.needLimit()){
            PageHelper.startPage(roleDto.getPage(), roleDto.getPageSize());
        }
        List<RoleVo> entities = roleDao.list(roleDto);
        return new PageUtils(new PageInfo<>(entities));
    }

    // 保存角色
    @Override
    @Transactional
    public R<?> save(RoleBO roleBO) {
        Long userId = Long.parseLong(SecurityHandler.getData().get(TokenConstants.USER_ID));
        roleBO.setCreateUser(userId);
        roleBO.setUpdateUser(userId);
        roleBO.setCreateTime(LocalDateTime.now());
        roleBO.setCreateTime(LocalDateTime.now());
        // 保存角色信息
        int roleInfo = roleDao.save(roleBO);
        if(roleInfo >0 && roleBO.getPermissionId().isEmpty()){
            return R.ok();
        }
        // 保存角色的权限
        int userRoleInfo = roleMenuService.saveRoleAuthority(roleBO.getId(), roleBO.getPermissionId());
        if(userRoleInfo>0){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @Override
    public RoleVo detail(Long id) {
        // 基本信息
        RoleVo vo = roleDao.detail(id);
        // 获取权限值
        List<Long> authority = roleMenuService.getAuthorityByRoleId(id);
        vo.setPermissionId(authority);
        return vo;
    }

    @Override
    @Transactional
    public void update(RoleBO roleBO) {
        // 修改基本信息
        Long userId = Long.parseLong(SecurityHandler.getData().get(TokenConstants.USER_ID));
        roleBO.setUpdateUser(userId);
        roleBO.setUpdateTime(LocalDateTime.now());
        roleDao.update(roleBO);
        // 删除权限信息
        roleMenuService.deleteByRoleId(Collections.singletonList(roleBO.getId()));
        //  重新插入权限信息
        roleMenuService.saveRoleAuthority(roleBO.getId(), roleBO.getPermissionId());
    }

    @Override
    public List<RoleVo> allRole() {
        return roleDao.allRole();
    }

    @Override
    @Transactional
    public void delete(List<Long> ids) {
        // 删除角色拥有的权限
        roleMenuService.deleteByRoleId(ids);
        // 删除角色拥有权限
        userRoleService.deleteByRoleId(ids);
        // 删除角色
        roleDao.delete(ids);
    }
}